package svgs

import "sort"

// Rect 矩形.
type Rect struct {
	X int
	Y int
	W int
	H int
}

// Rects 一组矩形.
type Rects struct {
	rects    []*Rect
	vertical bool
}

// NewRects 新建矩形数组.
func NewRects() *Rects {
	return &Rects{rects: []*Rect{}}
}

// Add 增加矩形.
func (r *Rects) Add(rects ...*Rect) {
	r.rects = append(r.rects, rects...)
}

// Len is the number of elements in the collection.
func (r *Rects) Len() int {
	return len(r.rects)
}

// Less reports whether the element with
// index i should sort before the element with index j.
func (r *Rects) Less(indexI, indexJ int) bool {
	if r.vertical {
		if r.rects[indexI].X == r.rects[indexJ].X {
			return r.rects[indexI].Y < r.rects[indexJ].Y
		}

		return r.rects[indexI].X < r.rects[indexJ].X
	}

	if r.rects[indexI].Y == r.rects[indexJ].Y {
		return r.rects[indexI].X < r.rects[indexJ].X
	}

	return r.rects[indexI].Y < r.rects[indexJ].Y
}

// Swap swaps the elements with indexes i and j.
func (r *Rects) Swap(i, j int) {
	r.rects[i], r.rects[j] = r.rects[j], r.rects[i]
}

// Compress 压缩.
func (r *Rects) Compress() []*Rect {
	sort.Sort(r)

	rect := []*Rect{}
	oldRect := &Rect{X: -1, Y: -1}

	for _, a := range r.rects {
		if a.Y != oldRect.Y || oldRect.X+oldRect.W != a.X {
			oldRect = a
			rect = append(rect, a)
		} else {
			oldRect.W += a.W
		}
	}

	r.rects = rect
	r.vertical = true
	sort.Sort(r)

	rect = []*Rect{}
	oldRect = &Rect{X: -1, Y: -1}

	for _, a := range r.rects {
		if a.X != oldRect.X || oldRect.Y+oldRect.H != a.Y || a.W != oldRect.W {
			oldRect = a
			rect = append(rect, a)
		} else {
			oldRect.H += a.H
		}
	}

	return rect
}
